from PySide6.QtCore import Qt
from PySide6.QtGui import QColor
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QWidget, QTableWidgetItem

from tools.data_process import DataProcess


class Window:
    ui = None
    cycle = 0
    history = None
    tail = 5

    def __init__(self):
        # 从文件中加载UI定义
        self.ui: QWidget = QUiLoader().load("./ui/signal_table.ui")
        self.ui.option.currentIndexChanged.connect(self.handle)

    def handle(self):
        self.ui.table.setRowCount(0)
        option = self.ui.option.currentText()
        data_process = DataProcess(option)
        self.history = data_process.history_data
        print("history is %s" % self.history)
        data = data_process.process()
        data_sorted = self.sorted_dict(data)
        self.fill(data_sorted)
        print("cycle number is %d" % self.cycle)
        self.cycle += 1

    def sorted_dict(self, data):
        sorted_data = dict(sorted(data.items(), key=lambda item: item[0]))
        return sorted_data

    def fill(self, data):
        for index, value in data.items():
            self.ui.table.insertRow(0)
            item = QTableWidgetItem(index)
            item.setTextAlignment(Qt.AlignCenter)
            self.ui.table.setItem(0, 0, item)
            item = QTableWidgetItem(str(value))
            item.setBackground(QColor(0, 255, 0))
            item.setTextAlignment(Qt.AlignCenter)
            self.ui.table.setItem(0, 1, item)
            if len(self.history[index]) < self.tail:
                for i in range(len(self.history[index])):
                    item = QTableWidgetItem(str(self.history[index][i]))
                    item.setTextAlignment(Qt.AlignCenter)
                    self.ui.table.setItem(0, i + 2, item)
            else:
                for i in range(2, self.tail + 2, 1):
                    item = QTableWidgetItem(str(self.history[index][i - 2]))
                    item.setTextAlignment(Qt.AlignCenter)
                    self.ui.table.setItem(0, i, item)
